<script lang="ts" setup>
import { ref, type PropType } from 'vue';
import type { FormInstance } from '@arco-design/web-vue/es/form';
import { $fetch } from '@/settings/utils/fetch';

const props = defineProps({
  id: {
    type: String,
    default: '',
  },
  nickname: {
    type: String,
    default: '',
  },
  username: {
    type: String,
    default: '',
  },
  roles: {
    type: Array as PropType<string[]>,
    default: () => ([]),
  },
});

const formData = ref({
  roles: props.roles,
});
const formRef = ref<FormInstance>();
const permission = ref(props.roles.length > 0 ? 'editor' : 'member');

const dialogClickButton = async (button: string) => {
  if (button !== 'ok') {
    return;
  }

  const res = await formRef.value?.validate();

  if (res) {
    return false;
  }

  const { isSuccess } = await $fetch('/admin/user/updateUserRole', {
    method: 'post',
    data: {
      userId: props.id,
      roles: permission.value === 'editor' ? formData.value.roles : [],
    },
  });

  return isSuccess;
}

defineExpose({
  dialogClickButton,
});
</script>

<template>
  <AForm ref="formRef" auto-label-width scroll-to-first-error :model="formData">
    <AFormItem :label="$t('settings.view.people.edit.column1')">
      {{ props.nickname }}
    </AFormItem>

    <AFormItem :label="$t('settings.view.people.edit.column2')">
      {{ props.username }}
    </AFormItem>

    <AFormItem :label="$t('settings.view.people.edit.column3')">
      <ARadioGroup v-model="permission">
        <ARadio value="member">{{ $t('settings.view.people.edit.status.1') }}</ARadio>
        <ARadio value="editor">{{ $t('settings.view.people.edit.status.2') }}</ARadio>
      </ARadioGroup>
    </AFormItem>

    <AFormItem field="roles" :label="$t('settings.view.people.edit.column4')" :rules="[{ required: true, message: $t('settings.notification.required') }]" v-if="permission === 'editor'">
      <ACheckboxGroup v-model="formData.roles">
        <ACheckbox value="editor">{{ $t('settings.view.people.edit.status.3') }}</ACheckbox>
      </ACheckboxGroup>
    </AFormItem>
  </AForm>
</template>

<style lang="scss" scoped>
</style>
